const Subscription = require('egg').Subscription;

class SmsTask extends Subscription {
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      // interval: '3m', // 1 分钟间隔
      // type: 'all', // 指定所有的 worker 都需要执行
      cron: '0 */10 * * * *',
      type: 'all',
    };
  }

  // subscribe 是真正定时任务执行时被运行的函数
  async subscribe() {
    const sms = await this.ctx.app.model.Sms.find({
      status: '10',
    });

    const apis = sms.map(item => {
      return this.ctx.app.sms.query({
        // customerCode: 'NM',
        // mobile: item.phone,
        queryId: item.sms_id,
      });
    });

    const results = await Promise.all(apis);

    const doing = results.map((item, index) => {
      return async function () {
        if (item.resultCode === '0000') {
          await this.ctx.app.model.Sms.update({
            _id: sms[index]._id,
          }, {
            status: '50',
            update_time: new Date()
          });

          return `短信记录：${sms[index].sms_id}，发送成功`;
        } else if (item.resultCode === '1000') {
          return `短信记录: ${sms[index].sms_id}, 正在发送中`;
        } else {
          await this.ctx.app.model.Sms.update({
            _id: sms[index]._id,
          }, {
            status: '60',
            update_time: new Date()
          });
          return `短信记录：${sms[index].sms_id}，发送失败`;
        }

      }.call(this);
    });

    const done = await Promise.all(doing);
    this.ctx.app.logger.info(done);
  }
}

module.exports = SmsTask;
